from robot.api import logger
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

from Lib.zcm.common.ui.PageElement import PageElement, By
from Lib.zcm.exception.TestException import TestException
from Lib.zcm.exception.errorcode import ErrorCode
from .antd_page_element import AntdPageElement


class DatePicker(AntdPageElement):

    def setValue(self, dates_str: str):
        """ 设置时间
        :param dateStr: 传入时间格式 如 "2014-09-15", 如果是一个时间段，以逗号分隔，如"2014-09-15,2015-09-14"
        :return:
        """
        self.wait_element_presence()

        # 首先点击，出来日期选择框
        self._get_web_element().click()
        # 找到实际输入框
        input_elements, show_elements = self._find_input_element()

        dates = dates_str.split(',')
        if len(dates) > len(input_elements):
            raise TestException.by_error_code(ErrorCode.DATE_PICKER_SET_FAILED, datestr=dates_str)

        # 输入时间
        for i, date_str in enumerate(dates):
            # 先清除内容，不能用clear，会导致弹出的输入框消失
            input_elements[i].send_keys(Keys.BACK_SPACE*30)
            input_elements[i].send_keys(date_str+'\n')
            # 检验
            value = show_elements[i].get_attribute('value')
            logger.debug(f"read datetime {value}")
            if value != date_str:
                logger.error(TestException.by_error_code(ErrorCode.DATE_PICKER_SET_FAILED, datestr=dates_str))


    def _find_input_element(self):
        # 找到显示的输入框，输入成不成功，要跟显示的输入框里的内容对比下
        element = self._get_web_element()

        if element.tag_name == 'input':
            show_input_elements = [element]
        else:
            show_input_elements = element.find_elements(By.TAG_NAME, 'input')

        # 找到实际输入的框
        if self.is_antd_version_4x():
            input_elements = show_input_elements
        elif self.is_antd_version_3x():
            # 找到弹出的输入框
            input_elements = self._driver.find_elements_by_css_selector('div.ant-calendar-picker-container input.ant-calendar-input')
        else:
            raise TestException.by_error_code(ErrorCode.UN_SUPPORT_ELEMENT, selector=str(self))

        if len(input_elements) <= 0:
            raise TestException.by_error_code(ErrorCode.UN_SUPPORT_ELEMENT, selector=str(self))

        # 如果都是只读的，那就有问题
        for input_element in input_elements:
            is_readonly = input_element.get_attribute('readonly')
            if is_readonly is None or is_readonly != 'true':
                break
        else:
            raise TestException.by_error_code(ErrorCode.UN_SUPPORT_ELEMENT, selector=str(self))
        return input_elements, show_input_elements

    def get_identification(self):
        identification = {'class': ['ant-calendar-picker']}
        return identification




